package com.example.miaosha.common.token;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * tokenKey获取工具类
 *
 * @author chensc
 * @date 2021-07-20
 */
@Slf4j
public class TokenCookieKeyUtil {

    /**
     * 获取伙伴端token key
     *
     * @param env 当前启动环境
     * @return
     */
    public static String getHbTokenCookieKey(String env) {
        return HbCookieKeyUtil.getCookieTokenKey(env);
    }

    /**
     * 获取主站token key
     *
     * @return
     */
    public static String getMainSiteTokenCookieKey() {
        return "IBOSS-WEB-TOEKN";
    }

    /**
     * 清除用户端token
     *
     * @param env
     * @param response
     */
    private static void clearCookieForMainSite(String env, HttpServletResponse response) {
        log.info("清除用户端cookie");
        Cookie icCookie = new Cookie("IBOSS-WEB-TOEKN", "");
        icCookie.setPath("/");
        icCookie.setDomain("gongsibao.com");
        icCookie.setMaxAge(0);
        response.addCookie(icCookie);
    }

//    /**
//     * 清除cookie
//     *
//     * @param platform 平台
//     * @param env      环境
//     * @param response
//     */
//    public static void clearCookie( String env, HttpServletResponse response) {
//            clearCookieForPartner(env, response);
//    }

    /**
     * 清除伙伴端token
     *
     * @param env
     * @param response
     */
    public static void clearCookieForPartner(String env, HttpServletResponse response) {
        log.info("清除伙伴端cookie");
        String tokenKey = HbCookieKeyUtil.getCookieTokenKey(env);
        if (!"prod".equals(env)) {
            Cookie cookie1 = new Cookie(tokenKey, "");
            cookie1.setPath("/");
            cookie1.setMaxAge(0);
            response.addCookie(cookie1);
        }
        Cookie cookie = new Cookie(tokenKey, "");
        cookie.setPath("/");
        cookie.setDomain("gongsibao.com");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public static class HbCookieKeyUtil {
        private static final String COOKIE_TOKEN_KEY = "HB-TOKEN";
        private static final String COOKIE_TOKEN_KEY_TEST = "HB-TOKEN-TEST";
        private static final String COOKIE_TOKEN_KEY_STAGE = "HB-TOKEN-STAGE";

        public static String getCookieTokenKey(String env) {
            switch (env) {
                case EnvType.DEV:
                case EnvType.TEST:
                    return COOKIE_TOKEN_KEY_TEST;
                case EnvType.STAGE:
                    return COOKIE_TOKEN_KEY_STAGE;
                case EnvType.PROD:
                default:
                    return COOKIE_TOKEN_KEY;
            }
        }

        private interface EnvType {
            String DEV = "dev";
            String TEST = "test";
            String STAGE = "stage";
            String PROD = "prod";
        }
    }
}
